
package hasthi.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * This is a bounded pool which remove objects inside it in 
 * least recently used fashion. The Head of the queue is object 
 * to be removed next. 
 * @author Srinath Perera(hperera@cs.indiana.edu)
 */
public class BoundedPool<E> {
    private Map<String, E> map = new HashMap<String, E>();
    private List<String> names = new ArrayList<String>();
    private int maxSize;
    
    public BoundedPool(int maxSize){
        this.maxSize = maxSize;
    }
    
    public synchronized E find(String name){
        E o =  map.get(name);
        if(o != null){
            //if object is present, move it to top
            names.remove(name);
            names.add(name);
        }
        return o;
    }
    
    public synchronized void add(String name,E o){
        names.add(name);
        map.put(name, o);
        //add this one, and remove last guy in the queue
        if(maxSize < names.size()){
            map.remove(names.remove(0));
        }
    }
}    

